import { setToken, removeToken } from 'utils/auth'
import { setStore, getStore } from 'utils/store'
import { encryption, deepClone } from 'utils/util'
import { loginByUsername, getUserInfo, getMenu, getTopMenu, logout, refreshToken } from '@/api/user'
import { login, logout1 } from "@/api/login"
import { formatPath } from '@/router/avue-router'
import Layout from '@/page/index/index.vue'
function randomColor() {
  return '#' + Math.random().toString(16).substr(2, 6).toUpperCase();
}
const user = {
  state: {
    userInfo: {},
    permission: {},
    roles: [],
    menuId: {},
    menu: getStore({ name: 'menu' }) || [],
    menuAll: getStore({ name: 'menuAll' }) || [],
    token: getStore({ name: 'token' }) || '',
    refreshToken: getStore({ name: 'token' }) || ''
  },
  actions: {
    //根据用户名登录
    LoginByUsername({ commit }, userInfo = {}) {
      // const user = encryption({
      //   data: userInfo,
      //   type: 'Aes',
      //   key: 'avue',
      //   param: ['useranme', 'password']
      // });

      return new Promise((resolve) => {
        //   loginByUsername(user.userName, user.password, userInfo.code, userInfo.captchaKey).then(res => {
        //     const data = res.data.data;
        //     commit('SET_TOKEN', data);
        //     commit('SET_REFRESH_TOKEN', data);
        //     commit('DEL_ALL_TAG', []);
        //     commit('CLEAR_LOCK');
        //     resolve();
        //   })
        login(userInfo).then(res => {
          localStorage.setItem('satoken', res.data.token);
          localStorage.setItem('userInfo', JSON.stringify(res));
          const data = res.data.token;
          commit('SET_TOKEN', data);
          commit('SET_REFRESH_TOKEN', data);
          commit('DEL_ALL_TAG', []);
          commit('CLEAR_LOCK');
          resolve();
        })
      })
    },
    //根据手机号登录
    LoginByPhone({ commit }, userInfo) {
      return new Promise((resolve) => {
        loginByUsername(userInfo.phone, userInfo.code).then(res => {
          const data = res.data.data;
          commit('SET_TOKEN', data);
          commit('DEL_ALL_TAG', []);
          commit('CLEAR_LOCK');
          resolve();
        })
      })
    },
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        let data = {
          userInfo: {
            username: 'admin',
            name: 'avue',
            avatar: 'https://gitee.com/uploads/61/632261_smallweigit.jpg',
          },
          roles: 'admin',
          permission: [
            'sys_crud_btn_add',
            'sys_crud_btn_export',
            'sys_menu_btn_add',
            'sys_menu_btn_edit',
            'sys_menu_btn_del',
            'sys_role_btn1',
            'sys_role_btn2',
            'sys_role_btn3',
            'sys_role_btn4',
            'sys_role_btn5',
            'sys_role_btn6',
          ]
        }
        // getUserInfo().then((res) => {
        // const data = res.data.data;
        commit('SET_USERIFNO', data.userInfo);
        commit('SET_ROLES', data.roles);
        commit('SET_PERMISSION', data.permission)
        resolve(data);
        // }).catch(err => {
        //   reject(err);
        // })
      })
    },
    //刷新token
    RefreshToken({ state, commit }) {
      return new Promise((resolve, reject) => {
        refreshToken(state.refreshToken).then(res => {
          const data = res.data.data;
          commit('SET_TOKEN', data);
          commit('SET_REFRESH_TOKEN', data);
          resolve(data);
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout1().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '');
          commit('SET_MENUALL_NULL', []);
          commit('SET_MENU', [])
          commit('SET_ROLES', [])
          commit('DEL_ALL_TAG', []);
          commit('CLEAR_LOCK');
          window.localStorage.clear()
          window.sessionStorage.clear();
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    //注销session
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        logout1().then(() => {
          window.localStorage.clear()
          window.sessionStorage.clear();
        })
        commit('SET_TOKEN', '')
        commit('SET_REFRESH_TOKEN', '');
        commit('SET_MENUALL_NULL', []);
        commit('SET_MENU', [])
        commit('SET_ROLES', [])
        commit('DEL_ALL_TAG', []);
        commit('CLEAR_LOCK');
        removeToken()
        resolve()
      })
    },
    GetTopMenu() {
      return new Promise(resolve => {
        const data = [
          {
            label: "首页",
            path: "/wel/index",
            icon: 'el-icon-document',
            meta: {
              i18n: 'dashboard',
            },
            parentId: 0
          },
        ]
        // getTopMenu().then((res) => {
        //   const data = res.data.data || []
        resolve(data)
        // })
      })
    },

    //获取系统菜单
    GetMenu({ commit }, parentId) {
      return new Promise(resolve => {
        const data1 = [
          {
            label: '商家',
            path: '/merchant',
            iconBgColor: randomColor(),
            children: [
              {
                label: '商圈好店',
                path: 'goodShop',
                iconBgColor: randomColor(),
                children: [
                  {
                    label: '分类列表',
                    path: 'classification',
                    iconBgColor: randomColor(),
                    component: 'views/merchant/goodShop/classification/index',
                  },
                  {
                    label: '商圈列表',
                    path: 'businessDistrict',
                    iconBgColor: randomColor(),
                    component: 'views/merchant/goodShop/businessDistrict/index',
                  },
                ]
              },
              {
                label: '商家管理',
                path: 'merchantManagement',
                iconBgColor: randomColor(),
                children: [
                  {
                    label: '商家列表',
                    path: 'businessListings',
                    iconBgColor: randomColor(),
                    component: 'views/merchant/merchantManagement/businessListings/index',
                  },
                  {
                    label: '商家入驻',
                    path: 'merchantsSettleIn',
                    iconBgColor: randomColor(),
                    component: 'views/merchant/merchantManagement/merchantsSettleIn/index',
                  },
                ]
              },
              {
                label: '商家结算',
                path: 'settlement',
                iconBgColor: randomColor(),
                children: [
                  {
                    label: '结算列表',
                    path: 'settlementList',
                    iconBgColor: randomColor(),
                    component: 'views/merchant/settlement/settlementList/index',
                  },
                  {
                    label: '体现申请',
                    path: 'reflectionList',
                    iconBgColor: randomColor(),
                    component: 'views/merchant/settlement/reflectionList/index',
                  },
                  {
                    label: '余额体现',
                    path: 'balanceList',
                    iconBgColor: randomColor(),
                    component: 'views/merchant/settlement/balanceList/index',
                  },
                ]
              },
            ]
          },
          {
            label: '系统',
            path: '/system',
            iconBgColor: randomColor(),
            children: [
              {
                label: '权限',
                path: 'permission',
                iconBgColor: randomColor(),
                children: [
                  {
                    label: "角色管理",
                    path: 'roles',
                    component: 'views/system/permission/roles/index',
                    icon: 'icon-caidan',
                    iconBgColor: randomColor(),
                    children: []
                  },
                  {
                    label: "员工管理",
                    path: 'staffManagement',
                    component: 'views/system/permission/staffManagement/index',
                    icon: 'icon-caidan',
                    iconBgColor: randomColor(),
                    children: []
                  },
                  {
                    label: "菜单管理",
                    path: 'menuSettings',
                    component: 'views/system/permission/menuSettings/index',
                    icon: 'icon-caidan',
                    iconBgColor: randomColor(),
                    children: []
                  },
                ]
              }
            ]
          },
          {
            path: '/logRecording',
            label: '日志记录',
            iconBgColor: randomColor(),
            component: 'views/logRecording/index',
            children: []
          },
        ]

        getMenu().then((res) => {
          if (res.code == 200) {
            const data = res.data
            let menu = deepClone(data);
            menu.forEach(ele => formatPath(ele, true));
            commit('SET_MENUALL', menu)
            commit('SET_MENU', menu)
            resolve(menu)
          }
        })
      })
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      setToken(token)
      state.token = token;
      setStore({ name: 'token', content: state.token })
    },
    SET_REFRESH_TOKEN: (state, token) => {
      state.refreshToken = token;
      setStore({ name: 'refreshToken', content: state.token })
    },
    SET_MENUID(state, menuId) {
      state.menuId = menuId;
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_MENUALL: (state, menuAll) => {
      let menu = state.menuAll;
      menuAll.forEach(ele => {
        let index = menu.findIndex(item => item.path == ele.path)
        if (index == -1) {
          menu.push(ele);
        } else {
          menu[index] = ele;
        }
      })
      state.menuAll = menu
      setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_MENUALL_NULL: (state) => {
      state.menuAll = []
      setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      setStore({ name: 'menu', content: state.menu })
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSION: (state, permission) => {
      state.permission = {};
      permission.forEach(ele => {
        state.permission[ele] = true;
      });
    }
  }

}
export default user